package com.demo.common.constant.api.base;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;


public class BaseServiceImpl<T, K> implements BaseService<T, K> {
    @Autowired
    protected BaseMapper<T, K> baseMapper;

    //当前泛型的真实类型Class
    private Class<T> modelClass;

    //构造函数
    public BaseServiceImpl() {
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        modelClass = (Class<T>) pt.getActualTypeArguments()[0];
    }

    //查询所有记录
    @Override
    public List<T> findAll() {
        return baseMapper.selectAll();
    }

    //根据ID查询
    @Override
    public T findById(K id) {
        return baseMapper.selectById(id);
    }

    //多条件查询
    @Override
    public List<T> findByParams(Map<String, String> map) {
        return baseMapper.selectByParams(map);
    }

    //查询记录总数
    @Override
    public int findAllCount() {
        return baseMapper.selectAllCount();
    }

    //分页读
    @Override
    public PageInfo<T> findPage(Map<String, String> map, Integer pageNum, Integer pageSize) {
        List<T> lists;
        PageInfo<T> pageInfo;

        // TODO Auto-generated method stub
        PageHelper.startPage(pageNum, pageSize);

        lists = baseMapper.selectByParams(map);
        pageInfo = new PageInfo<T>(lists);

        return pageInfo;
    }

    //插入
    @Override
    public boolean add(T entity) {
        return baseMapper.insert(entity) > 0;
    }

    //修改
    @Override
    public boolean modify(T entity) {
        //System.out.println(entity);
        return baseMapper.update(entity) > 0;
    }

    //多条件修改
    @Override
    public boolean modifyByParams(T entity) {
        return baseMapper.updateByParams(entity) > 0;
    }

    //删除
    @Override
    public boolean remove(K id) {
        return baseMapper.delete(id) > 0;
    }

    //根据ID批量删除
    @Override
    public boolean batchRemove(List<K> ids) {
        return baseMapper.batchDelete(ids) > 0;
    }

    //多条件删除
    @Override
    public boolean removeByParams(Map<String, String> map) {
        return baseMapper.deleteByParams(map) > 0;
    }
}
